﻿using Arch.Samples.RiaServices.Commands;
using Arch.Samples.RiaServices.Services;
using Arch.Samples.Model;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Arch.Samples.RiaServices.Infrastructure;
using Arch.Samples.RiaServices.Views.Todos;

namespace Arch.Samples.RiaServices.ViewModels
{
    public class TodoListViewModel : CollectionViewModelBase<Todo>
    {
        public TodoListViewModel(TodoContext context) : base(context)
        {
            SubCategories = new ObservableCollection<SubCategory>();
            GlobalCategories = new ObservableCollection<GlobalCategory>();

            AddCommand = new AddCommand<TodoListViewModel, Todo, TodoEdit>(this, e => Context.Todos.Add(e));
            EditCommand = new EditCommand<TodoListViewModel, Todo, TodoEdit>(this);
            DeleteCommand = new DeleteCommand<TodoListViewModel, Todo>(this, e => Context.Todos.Remove(e));
            DeleteSelectedCommand = new DeleteSelectedCommand<TodoListViewModel, Todo>(this, e => Context.Todos.Remove(e));

            Refresh();
        }

        public ICollection<SubCategory> SubCategories { get; set; }
        public ICollection<GlobalCategory> GlobalCategories { get; set; }

        public void LoadSubCategories()
        {
            Context.Load(Context.GetSubCategoryQuery(), l => SubCategories.Reload(l.Entities), true);
        }

        public void LoadGlobalCategories()
        {
            Context.Load(Context.GetGlobalCategoryQuery(), l => GlobalCategories.Reload(l.Entities), true);
        }

        private void LoadTodos()
        {
            Context.Load(Context.GetTodoQuery(), l => Items.Reload(l.Entities));
        }

        public override void Refresh()
        {
            LoadGlobalCategories();
            LoadSubCategories();
            LoadTodos();
        }
    }
}
